<template>
  <div>
    <!--引用表格-->
    <BasicTable @register="registerTable" :rowSelection="rowSelection">
      <!--插槽:table标题-->
      <template #tableTitle>
        <a-button type="primary" @click="handleAdd" preIcon="ant-design:plus-outlined"> 新增</a-button>
        <a-button type="primary" preIcon="ant-design:export-outlined" @click="onExportXls"> 导出</a-button>
        <j-upload-button type="primary" preIcon="ant-design:import-outlined" @click="onImportXls">导入</j-upload-button>
        <a-dropdown v-if="selectedRowKeys.length > 0">
          <template #overlay>
            <a-menu>
              <a-menu-item key="1" @click="batchHandleDelete">
                <Icon icon="ant-design:delete-outlined"></Icon>
                删除
              </a-menu-item>
            </a-menu>
          </template>
          <a-button
            >批量操作
            <Icon icon="mdi:chevron-down"></Icon>
          </a-button>
        </a-dropdown>
      </template>
      <!--操作栏-->
      <template #action="{ record }">
        <TableAction :actions="getTableAction(record)" />
      </template>
    </BasicTable>

    <!-- 表单区域 -->
    <LicenseModal @register="registerLicenseModal" @success="handleSuccess"></LicenseModal>

    <GenerateLicenseModal @register="registerGenerateModal" @success="handleSuccess"/>

  </div>
</template>

<script lang="ts" name="license-license" setup>
  import {ref, computed, unref} from 'vue';
  import {BasicTable, useTable, TableAction} from '/@/components/Table';
  import { BasicModal, useModal } from '/@/components/Modal';
  import { useListPage } from '/@/hooks/system/useListPage'
  import LicenseModal from './modules/LicenseModal.vue'
  import {columns, searchFormSchema} from './License.data';
  import { list, deleteOne, batchDelete, getImportUrl, getExportUrl, generateLicense, downloadLicenseFile } from "./License.api";
  import { createMessage } from 'ant-design-vue';
  import { useMessage } from '@/hooks/web/useMessage';
  const { createMessage } = useMessage();
  import GenerateLicenseModal from './modules/GenerateLicenseModal.vue';
  //注册model
  const [registerLicenseModal, {openModal:openLicenseModal }] = useModal();
  const [registerGenerateModal, {openModal:openGenerateModal }] = useModal();
  //注册table数据
  const { prefixCls,tableContext,onExportXls,onImportXls } = useListPage({
       tableProps:{
            title: 'license操作',
            api: list,
            columns,
            canResize:false,
            formConfig: {
               labelWidth: 120,
               schemas: searchFormSchema,
               autoSubmitOnEnter:true,
               showAdvancedButton:true,
             },
            actionColumn: {
                width: 300,
             },
        },
        exportConfig: {
             name:"license操作",
             url: getExportUrl,
           },
           importConfig: {
             url: getImportUrl
           },
   })

   const [registerTable, {reload},{ rowSelection, selectedRowKeys }] = tableContext

  const handleDownload = async (record : Record<string, any>) => {
    try {
      const params = {
        id: record.id,
        // fileName: 'license_package.zip'
        fileName: 'license.lic'
      };
      const res = await downloadLicenseFile(params);
      if (!(res instanceof Blob)) {
        alert('文件下载失败');
        return;
      }
      // 创建临时链接并触发下载
      const url = window.URL.createObjectURL(new Blob([res]));
      const link = document.createElement('a');
      link.href = url;
      link.setAttribute('download', `${params.fileName}`); // 设置下载文件名
      document.body.appendChild(link);
      link.click();
      link.remove(); // 清理 DOM
      window.URL.revokeObjectURL(url); // 释放内存
    } catch (error) {
      console.error('下载失败:', error);
      alert('下载失败，请重试');
    }
  };
   /**
    * 新增事件
    */
   function handleAdd() {
     openLicenseModal(true, {
       isUpdate: false,
       showFooter: true,
     });
   }
   /**
    * 编辑事件
    */
  function handleEdit(record: Recordable) {
     openLicenseModal(true, {
       record,
       isUpdate: true,
       showFooter: true,
     });
   }
   /**
    * 详情
   */
  function handleDetail(record: Recordable) {
     openLicenseModal(true, {
       record,
       isUpdate: true,
       showFooter: false,
     });
   }
   /**
    * 删除事件
    */
   async function handleDelete(record) {
     await deleteOne({id: record.id}, reload);
   }
   /**
    * 批量删除事件
    */
   async function batchHandleDelete() {
     await batchDelete({ids: selectedRowKeys.value}, reload);
   }
   /**
    * 成功回调
    */
   function handleSuccess({isUpdate, values}) {
      reload();
   }

   // function createLicience( record){
   //   generateLicense(record, reload);
   // }
   async function handleGenerateLicense(record){

     // const machineCode = window.prompt('请输入 machineCode:');
     // if (machineCode) {
     //   try {
     //     const params = {...record, machineCode};
     //     await generateLicense(params,reload);
     //     createMessage.success('许可证生成成功');
     //   } catch (error) {
     //     createMessage.error('许可证生成失败，请重试');
     //   }
     // } else {
     //   createMessage.warning('machineCode 不能为空');
     // }
     openGenerateModal(true, {
       record,
       isUpdate: true,
       showFooter: true });
     //获取输入的machineCode
   }

   /**
      * 操作栏
      */
   function getTableAction(record){
       return [
         {
           label: '编辑',
           onClick: handleEdit.bind(null, record),
         },{
           label: '许可证生成',
           onClick: handleGenerateLicense.bind(null, record),
         }, {
           label: '下载证书',
           // 判断是否显示“下载证书”按钮
           ifShow: record.licenseFileGenerated === 1,
           onClick: (e) => {
             console.log('licenseFileGenerated类型:', typeof record.licenseFileGenerated);
             console.log('licenseFileGenerated值:', record.licenseFileGenerated);
             if(record.licenseFileGenerated !== 1)
             {
               createMessage.error('必须生成许可证才能进行许可证下载');
               e.preventDefault();
               return;
             }
             handleDownload(record);
           }
         }, {
           label: '删除',
           popConfirm: {
             title: '是否确认删除',
             confirm: handleDelete.bind(null, record),
           }
         }
       ]
     }
</script>
<style scoped></style>
